#include "CocosPCH.h"
#include "CoCElementShape.h"
#include "CoCSWF.h"
#include "CoCElementTexture.h"

#include "Utility.h"
#include <assert.h>

struct Point
{
	int x,y;
};

struct UV
{
	short x,y;
};


CoCElementShape::CoCElementShape(void)
	: m_pVertex(NULL)
{
}


CoCElementShape::~CoCElementShape(void)
{
	if(m_pVertex)
		delete [] m_pVertex;
}

bool CoCElementShape::Parse(void *data, CoCSWF *pSWF)
{		
	int nDataPos = 0;
	unsigned short m_nCommandCount;
	Utility_ReadValue(&m_nID, data, &nDataPos);
	Utility_ReadValue(&m_nCommandCount, data, &nDataPos);
		
	unsigned short nVertxtCount;
	Utility_ReadValue(&nVertxtCount, data, &nDataPos);

    m_pVertex = new V3F_C4B_T2F[nVertxtCount];
    V3F_C4B_T2F *pVertex = m_pVertex;
	m_vecShaps.resize(m_nCommandCount);
	
	int nTotalCount = 0;
	for(unsigned short i = 0; i < m_nCommandCount; i++)
	{
		char cType;
		Utility_ReadValue(&cType, data, &nDataPos);
		int nLength;
		Utility_ReadValue(&nLength, data, &nDataPos);

		ShapInfo &shaps = m_vecShaps[i];
		Utility_ReadValue(&shaps.textureID, data, &nDataPos);
		char cPointCount;
		Utility_ReadValue(&cPointCount, data, &nDataPos);
		shaps.vertex = pVertex;
		shaps.count = cPointCount;
		nTotalCount += cPointCount;

		CoCElementTexture *pTexture = pSWF->GetTexture(shaps.textureID);
		unsigned short nWidth = pTexture->GetWidth();
		unsigned short nHeight = pTexture->GetHeight();
		
		for(int j = 0; j < cPointCount; j++)
		{
			pVertex[j].vertices.x = *((int*)((char*)data+nDataPos)) / 20.0f;
			pVertex[j].vertices.y = *((int*)((char*)data+nDataPos)+1) / -20.0f;
			pVertex[j].vertices.z = 0.0f;
			nDataPos += 8;
			pVertex[j].colors.a = 255;
			pVertex[j].colors.r = 255;
			pVertex[j].colors.g = 255;
			pVertex[j].colors.b = 255;
		}
		for(int j = 0; j < cPointCount; j++)
		{
			pVertex[j].texCoords.u = *((short*)((char*)data+nDataPos)) / (nWidth*1.0f);
			pVertex[j].texCoords.v = *((short*)((char*)data+nDataPos)+1) / (nHeight*1.0f);
			nDataPos += 4;
		}
		pVertex = pVertex + cPointCount;
	}

	assert(nTotalCount == nVertxtCount);
	return true;
}

ShapInfo *CoCElementShape::GetShapInfo(int nIndex)
{
	if(nIndex >= m_vecShaps.size())
	{
		return NULL;
	}
	return &m_vecShaps[nIndex];
}

int CoCElementShape::GetShapsCount()
{
	return m_vecShaps.size();
}

unsigned short CoCElementShape::GetID()
{
	return m_nID;
}